<template>
  <div class="admin-layout">
    <!-- 侧边栏 -->
    <div class="sidebar" :class="{ 'collapsed': isCollapsed }">
      <div class="sidebar-header">
        <div class="logo">
          <i class="el-icon-setting"></i>
          <span v-show="!isCollapsed" class="logo-text">管理系统</span>
        </div>
      </div>
      
      <el-menu
        :default-active="activeMenu"
        class="sidebar-menu"
        :collapse="isCollapsed"
        :unique-opened="true"
        background-color="#2c3e50"
        text-color="#ecf0f1"
        active-text-color="#3498db"
        @select="handleMenuSelect"
      >
        <el-menu-item index="dashboard">
          <el-icon><House /></el-icon>
          <span>仪表盘</span>
        </el-menu-item>

        <el-sub-menu index="symptom-management">
          <template #title>
            <el-icon><FirstAidKit /></el-icon>
            <span>症状汤药管理</span>
          </template>
          <el-menu-item index="symptom-category">
            <el-icon><Collection /></el-icon>
            <span>症状分类</span>
          </el-menu-item>
          <el-menu-item index="symptom">
            <el-icon><Warning /></el-icon>
            <span>症状管理</span>
          </el-menu-item>
          <el-menu-item index="formula">
            <el-icon><List /></el-icon>
            <span>汤药管理</span>
          </el-menu-item>
          <el-menu-item index="data-sync">
            <el-icon><Upload /></el-icon>
            <span>数据同步</span>
          </el-menu-item>
        </el-sub-menu>

        <el-menu-item index="settings">
          <el-icon><Setting /></el-icon>
          <span>系统设置</span>
        </el-menu-item>
      </el-menu>
    </div>
    
    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 头部 -->
      <div class="header">
        <div class="header-left">
          <el-button
            type="link"
            class="collapse-btn"
            @click="toggleSidebar"
          >
            <el-icon><Expand v-if="isCollapsed" /><Fold v-else /></el-icon>
          </el-button>
          
          <el-breadcrumb separator="/" class="breadcrumb">
            <el-breadcrumb-item>{{ currentPageTitle }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <div class="user-info">
              <el-avatar :size="32" :src="userAvatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="username">{{ userInfo.username }}</span>
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                <el-dropdown-item command="settings">账户设置</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      
      <!-- 内容区域 - 子路由渲染区 -->
      <div class="content-area">
        <div class="page-container">
          <router-view />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  House, User, Document, FirstAidKit, Money, Setting,
  Expand, Fold, ArrowDown, Collection, Warning, List, Upload
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 响应式数据
const isCollapsed = ref(false)
const activeMenu = ref('dashboard')
const userAvatar = ref('')

// 用户信息
const userInfo = reactive({
  username: 'admin',
  role: 'administrator'
})

// 页面标题映射
const pageTitleMap = {
  'dashboard': '仪表盘',
  'symptom-category': '症状分类管理',
  'symptom': '症状管理',
  'formula': '汤药管理',
  'data-sync': '数据同步管理',
  'settings': '系统设置'
}

// 当前页面标题
const currentPageTitle = computed(() => {
  return pageTitleMap[activeMenu.value] || '管理系统'
})

// 切换侧边栏
const toggleSidebar = () => {
  isCollapsed.value = !isCollapsed.value
}

// 处理菜单选择
const handleMenuSelect = (index) => {
  activeMenu.value = index
  // 根据菜单项跳转到对应路由
  const routeMap = {
    'dashboard': '/admin/dashboard',
    'symptom-category': '/admin/symptom-category',
    'symptom': '/admin/symptom',
    'formula': '/admin/formula',
    'data-sync': '/admin/data-sync',
    'settings': '/admin/settings'
  }
  
  const targetRoute = routeMap[index]
  if (targetRoute) {
    router.push(targetRoute)
  }
}

// 处理用户下拉菜单
const handleCommand = async (command) => {
  switch (command) {
    case 'profile':
      ElMessage.info('个人资料功能开发中...')
      break
    case 'settings':
      ElMessage.info('账户设置功能开发中...')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 清除登录状态
        localStorage.removeItem('admin_token')
        localStorage.removeItem('admin_user')
        
        ElMessage.success('已退出登录')
        router.push('/admin/login')
      } catch {
        // 用户取消
      }
      break
  }
}

// 检查登录状态
const checkAuth = () => {
  const token = localStorage.getItem('admin_token')
  const user = localStorage.getItem('admin_user')
  
  if (!token || !user) {
    router.push('/admin/login')
    return
  }
  
  try {
    const userData = JSON.parse(user)
    userInfo.username = userData.username
    userInfo.role = userData.role
  } catch {
    router.push('/admin/login')
  }
}

// 根据当前路由设置活动菜单
const setActiveMenuFromRoute = () => {
  const path = route.path
  
  // 路由到菜单项的反向映射
  const pathToMenuMap = {
    '/admin': 'dashboard',
    '/admin/': 'dashboard',
    '/admin/dashboard': 'dashboard',
    '/admin/symptom-category': 'symptom-category',
    '/admin/symptom': 'symptom',
    '/admin/formula': 'formula',
    '/admin/data-sync': 'data-sync',
    '/admin/settings': 'settings'
  }
  
  const menuKey = pathToMenuMap[path]
  if (menuKey) {
    activeMenu.value = menuKey
  }
}

// 监听路由变化
watch(() => route.path, () => {
  setActiveMenuFromRoute()
}, { immediate: true })

// 组件挂载时检查认证
onMounted(() => {
  checkAuth()
  setActiveMenuFromRoute()
})
</script>

<style lang="less" scoped>
.admin-layout {
  display: flex;
  height: 100vh;
  background-color: #f5f5f5;
}

// 侧边栏样式
.sidebar {
  width: 250px;
  background-color: #2c3e50;
  transition: width 0.3s;
  overflow: hidden;
  
  &.collapsed {
    width: 64px;
  }
  
  .sidebar-header {
    height: 60px;
    display: flex;
    align-items: center;
    padding: 0 20px;
    border-bottom: 1px solid #34495e;
    
    .logo {
      display: flex;
      align-items: center;
      color: #ecf0f1;
      font-size: 18px;
      font-weight: 600;
      
      i {
        font-size: 24px;
        margin-right: 10px;
      }
      
      .logo-text {
        transition: opacity 0.3s;
      }
    }
  }
  
  .sidebar-menu {
    border: none;
    
    :deep(.el-menu-item) {
      height: 50px;
      line-height: 50px;
      
      &:hover {
        background-color: #34495e !important;
      }
      
      &.is-active {
        // background-color: #3498db !important;
      }
    }
    
    :deep(.el-sub-menu__title) {
      height: 50px;
      line-height: 50px;
      
      &:hover {
        background-color: #34495e !important;
      }
    }
  }
}

// 主内容区样式
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

// 头部样式
.header {
  height: 60px;
  background: white;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  
  .header-left {
    display: flex;
    align-items: center;
    
    .collapse-btn {
      margin-right: 20px;
      font-size: 18px;
      color: #666;
      
      &:hover {
        color: #3498db;
      }
    }
    
    .breadcrumb {
      font-size: 16px;
    }
  }
  
  .header-right {
    .user-info {
      display: flex;
      align-items: center;
      cursor: pointer;
      padding: 8px 12px;
      border-radius: 6px;
      transition: background-color 0.3s;
      
      &:hover {
        background-color: #f5f5f5;
      }
      
      .username {
        margin: 0 8px;
        font-weight: 500;
      }
    }
  }
}

// 内容区域样式
.content-area {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
}

// 移动端适配
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    z-index: 1000;
    transform: translateX(-100%);
    transition: transform 0.3s;
    
    &.collapsed {
      width: 250px;
      transform: translateX(0);
    }
  }
  
  .main-content {
    width: 100%;
  }
}
</style>
